#-*- coding: UTF-8 -*-
import requests
import json
import sys
from pyquery import PyQuery as pq

class TbItemCrawler:

    def __init__(self):
	    pass

    def get_sku(self, goods_id):
        tb_url = "https://item.taobao.com/item.htm?id="
        goods_url = tb_url + goods_id
        result = requests.get(goods_url)
        html = pq(result.text)
        sku_html = html('dl').filter('.tb-prop').children('dd')
        if sku_html:
            sku_items = sku_html.items()
            sku_data = []
            #循环全部sku类
            for sku in sku_items:
                per_skus_name = sku('ul').attr('data-property')
                if per_skus_name:
                    per_sku_data = []
                    per_skus_html = sku('ul').children('li').items()
                    #子循环拿到单个sku具体值
                    for per_sku in per_skus_html:
                        per_sku_id = per_sku.attr('data-value')
                        per_sku_title = per_sku('a span').text()
                        per_sku_data.append({
                            'sku_id':per_sku_id,
                            'sku_title':per_sku_title
                        })
                    sku_data.append({
                        'name':per_skus_name,
                        'value':per_sku_data
                    })
                    result = {
                        'code':200,
                        'message':'success',
                        'data':sku_data
                    }
                else:
                    result = {
                        'code':100,
                        'message':'商品属性获取失败或属性不存在',
                        'data':'error'
                    }
                    break

        else:
            result = {
                'code':100,
                'message':'商品属性获取失败或属性不存在',
                'data':'error'
            }

        result_json = json.dumps(result)
        return result_json

def main():
    crawler = TbItemCrawler()
    goods_id = sys.argv[1]
    result = crawler.get_sku(goods_id)
    print(result)

if __name__ == '__main__':
    main()
